import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { MessageService } from 'src/app/service/message.service';

declare let AMap: any;
type AddressData = {
  userAddress: string,
  latitude: string,
  longitude: string
}

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit {

  @Input() addressLabel = '位置';
  @Input() isAble=false;
  @Input() defultValue: any;//默认值,回显值
  @Input() width: any = 'auto';
  @Output() locationInfo = new EventEmitter();

  formData: AddressData = {
    userAddress: '',
    longitude: '',
    latitude: ''
  };

  isSelect = 'none';
  userAddress = '';

  map: any;
  marker: any;

  constructor(
    private message: MessageService
  ) { }

  ngOnInit() {
    this.userAddress=this.defultValue;
    this.initMap();
    
    this._myLocation();
  }
  city = ''
  district = '';
  districtArr = ['越秀区', '荔湾区', '天河区', '海珠区', '黄埔区', '白云区'];
  initMap(){
    this.map = new AMap.Map("container", {
      resizeEnable: true,
      isHotspot: true,
    });
    this.map.setCity('广州市');
    let southWest = new AMap.LngLat(112.295987, 22.40961);
    let northEast = new AMap.LngLat(114.111478, 23.851782);
    let bounds = new AMap.Bounds(southWest, northEast);
    console.log(bounds);
    this.map.setLimitBounds(bounds);

    this.map.setZoom(13);  // 缩放比例

    this.map.on('hotspotclick', this._hotSpotClick);  // 点击地址

    this._autoComplete();
  }

  _hotSpotClick = (e: any) => {
    console.log(e);
    this._getAddress(e.lnglat);
  }
  _getAddress(lnglat: any){
    AMap.plugin('AMap.Geocoder', () => {
      var geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        // city: '010'
      })
    
      geocoder.getAddress(lnglat, (status: any, result: any) => {
        if (status === 'complete' && result.info === 'OK') {
            console.log(result);
            const cityCode = result.regeocode.addressComponent.citycode;
            
            if(cityCode !== '020'){ // city: "广州市"
              this.message.info('不属于我公司供水范围')
              return ;
            }
            this._addMarker(lnglat, result);

            this.formData.userAddress = result.regeocode.formattedAddress;
            this.formData.longitude = lnglat.lng;
            this.formData.latitude = lnglat.lat;
            this.district = result.regeocode.addressComponent.district;
            this.city = result.regeocode.addressComponent.city;
        }
      })
    })
  }
  _addMarker(lnglat: any, result: any){
    this._removeMarker();

    this.marker = new AMap.Marker({
      icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
      position: [lnglat.lng, lnglat.lat],
    });

    this.marker.on('click', (e: any) => {

      let info = [];
      info.push("<div style=\"padding:0px 0px 0px 4px;\">");
      // info.push("<p style=\"font-size:16px;\">高德软件</p>")
      info.push(`地址：${result.regeocode.formattedAddress}</div>`);


      let infoWindow = new AMap.InfoWindow({
          content: info.join(""),  //使用默认信息窗体框样式，显示信息内容
          position: e.lnglat,
          closeWhenClickMap: true
      });
      // infoWindow.on('open',showInfoOpen)
      // infoWindow.on('close',showInfoClose)
      infoWindow.open(this.map);
    })
  
    this.map.add(this.marker);
    this.map.setFitView();
  }
  _removeMarker(){
    if(this.marker){
      this.map.remove(this.marker);
      this.map.setFitView();
    }
  }

  _autoComplete(){
    AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'], () => {
      // 实例化Autocomplete
      let autoOptions = {
        //city 限定城市，默认全国
        city: '广州',
        citylimit: true,
        input: 'keyWord',
      }
      let autoComplete= new AMap.Autocomplete(autoOptions);
      let placeSearch = new AMap.PlaceSearch({
        city: '广州',
        map: this.map
      })
      AMap.event.addListener(autoComplete, "select", (e: any) => {
        let poi = e.poi;
        placeSearch.search(poi.name);

        let params: AddressData = {
          userAddress: poi.district + poi.name,
          longitude: poi.location.lng,
          latitude: poi.location.lat
        }
        this._setFormData(params)
      });
      placeSearch.on('markerClick', (e: any) => {
        console.log(e)
        let data = e.data;
        this.district = data.adname;
        this.city = data.cityname
        this.formData.userAddress = data.cityname + data.adname + data.name;
        let params: AddressData = {
          userAddress: data.cityname + data.adname + data.name,
          longitude: data.location.lng,
          latitude: data.location.lat
        }
        this._setFormData(params)
      })
    })
  }

  _setFormData(params: any){
    this.formData = params;
  }

  onFocus(){
    this.isSelect = 'flex';
  }

  onClose(e: any){
    e.preventDefault(); 
    this.isSelect = 'none';
  }

  // TODO 广州市
  onSubmit(e: any){
    e.preventDefault();  
    // if(this.util.mapOpenArea.indexOf(this.district) === -1){
    //   this.util.info(this.district +" 不在服务地区范围内");
    //   return ;
    // }
    console.log(e)
    if(this.city !== '广州市'){
      this.message.info(this.city +" 不在服务地区范围内");
      return ;
    }
    this.onClose(e);
    this.userAddress = this.formData.userAddress;
    this.locationInfo.emit(this.formData);
  }

  _myLocation(){
    AMap.plugin('AMap.Geolocation', () => {
      var geolocation = new AMap.Geolocation({
          enableHighAccuracy: false,//是否使用高精度定位，默认:true
          timeout: 30000,          //超过10秒后停止定位，默认：5s
          buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

      });
      this.map.addControl(geolocation);
      console.log(geolocation);
      geolocation.getCurrentPosition((status: any,result: any) => {
        console.log(result);
        if(status === 'complete'){
          console.log(result);
          // if(result.addressComponent.citycode !== '020' || this.util.mapOpenArea.indexOf(result.addressComponent.district) === -1){
          //   return ;
          // }
          this.city = result.addressComponent.city
          this.district = result.addressComponent.district;
          this.formData.userAddress = result.formattedAddress;
          this.formData.longitude = result.position.lng;
          this.formData.latitude = result.position.lat;
        }
      });
    });
  }



}
